import { Container, Grid, Typography, Card, CardContent, CardMedia, Box, Chip, Rating, CircularProgress, Alert, Pagination, Button, Paper } from '@mui/material';
import { Whatshot as WhatshotIcon, LocalOffer as LocalOfferIcon, Login as LoginIcon, HowToReg as RegisterIcon } from '@mui/icons-material';
import { useState, useEffect } from 'react';
import { ResourceService, Resource } from '../features/resources/services/ResourceService';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../features/auth/AuthContext';
import { motion } from 'framer-motion';

// 格式化文件大小的辅助函数
const formatSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return parseFloat((bytes / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i];
};

const mockPromotions = [
  {
    id: 1,
    title: '疯狂星期一',
    description: '每周一精选资源免费下载，不限量不限速！',
    image: '/covers/promotion_monday.jpg',
  },
  {
    id: 2,
    title: '新人特惠',
    description: '新注册用户送1000积分，享受7天会员特权',
    image: '/covers/newuser.png',
  },
];

const Home = () => {
  const [recommendedResources, setRecommendedResources] = useState<Resource[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const pageSize = 9;
  const navigate = useNavigate();
  const { user } = useAuth();

  // 获取推荐资源
  useEffect(() => {
    const fetchRecommendedResources = async () => {
      try {
        setLoading(true);
        setError(null);
        const response = await ResourceService.getRecommendedResources(page, pageSize);
        setRecommendedResources(response.records || []);
        // 计算总页数
        const total = response.total || 0;
        setTotalPages(Math.ceil(total / pageSize) || 1);
      } catch (err) {
        console.error('获取推荐资源失败:', err);
        setError(err instanceof Error ? err.message : '获取推荐资源失败');
      } finally {
        setLoading(false);
      }
    };

    fetchRecommendedResources();
  }, [page, pageSize]);

  const handleResourceClick = (resource: Resource) => {
    // 跳转到资源详情页
    navigate(`/resources/${resource.id}`);
  };

  // 登录按钮点击处理函数
  const handleLoginClick = () => {
    navigate('/login');
  };

  // 注册按钮点击处理函数
  const handleRegisterClick = () => {
    navigate('/register');
  };

  return (
    <Container maxWidth="lg" sx={{ py: 4 }}>
      {/* 未登录提示卡片 */}
      {!user && (
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
          <Paper 
            elevation={3} 
            sx={{ 
              p: 3, 
              mb: 4, 
              borderRadius: 2,
              background: 'linear-gradient(135deg, #6a11cb 0%, #2575fc 100%)',
              color: 'white',
              position: 'relative',
              overflow: 'hidden'
            }}
          >
            <Box sx={{ position: 'relative', zIndex: 2 }}>
              <Typography variant="h5" fontWeight="bold" gutterBottom>
                欢迎来到思源PT站点
              </Typography>
              <Typography variant="body1" sx={{ mb: 2, maxWidth: '80%' }}>
                登录后即可体验完整功能，包括资源下载、社区互动、好友系统等。新用户注册即送1000积分！
              </Typography>
              <Box sx={{ display: 'flex', gap: 2, mt: 2 }}>
                <Button 
                  variant="contained" 
                  color="secondary" 
                  startIcon={<LoginIcon />}
                  onClick={handleLoginClick}
                  sx={{ 
                    fontWeight: 'bold',
                    boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
                    '&:hover': { transform: 'translateY(-2px)', boxShadow: '0 6px 8px rgba(0,0,0,0.15)' }
                  }}
                >
                  立即登录
                </Button>
                <Button 
                  variant="outlined" 
                  startIcon={<RegisterIcon />}
                  onClick={handleRegisterClick}
                  sx={{ 
                    color: 'white', 
                    borderColor: 'white',
                    '&:hover': { 
                      borderColor: 'white', 
                      backgroundColor: 'rgba(255,255,255,0.1)',
                      transform: 'translateY(-2px)'
                    }
                  }}
                >
                  注册账号
                </Button>
              </Box>
            </Box>
            {/* 装饰性圆形背景 */}
            <Box sx={{ 
              position: 'absolute', 
              top: -30, 
              right: -30, 
              width: 150, 
              height: 150, 
              borderRadius: '50%', 
              backgroundColor: 'rgba(255,255,255,0.1)' 
            }} />
            <Box sx={{ 
              position: 'absolute', 
              bottom: -40, 
              right: 100, 
              width: 100, 
              height: 100, 
              borderRadius: '50%', 
              backgroundColor: 'rgba(255,255,255,0.1)' 
            }} />
          </Paper>
        </motion.div>
      )}

      {/* 活动展示区 */}
      <Box sx={{ mb: 6 }}>
        <Typography variant="h5" sx={{ mb: 2, display: 'flex', alignItems: 'center' }}>
          <LocalOfferIcon sx={{ mr: 1 }} color="primary" />
          热门活动
        </Typography>
        <Grid container spacing={3}>
          {mockPromotions.map((promotion) => (
            <Grid item xs={12} md={6} key={promotion.id}>
              <Card sx={{
                cursor: 'pointer',
                transition: 'all 0.3s ease',
                '&:hover': {
                  transform: 'translateY(-4px)',
                  boxShadow: 6,
                },
              }}>
                <CardMedia
                  component="img"
                  height="200"
                  image={promotion.image}
                  alt={promotion.title}
                />
                <CardContent>
                  <Typography gutterBottom variant="h6">
                    {promotion.title}
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    {promotion.description}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
          ))}
        </Grid>
      </Box>

      {/* 推荐资源区 */}
      <Box>
        <Typography variant="h5" sx={{ mb: 2, display: 'flex', alignItems: 'center' }}>
          <WhatshotIcon sx={{ mr: 1 }} color="error" />
          推荐资源
        </Typography>
        
        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
            <CircularProgress />
          </Box>
        ) : error ? (
          <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>
        ) : recommendedResources.length === 0 ? (
          <Alert severity="info" sx={{ mb: 2 }}>暂无推荐资源</Alert>
        ) : (
          <Grid container spacing={3}>
            {recommendedResources.map((resource) => (
              <Grid item xs={12} sm={6} md={4} key={resource.id}>
                <Card 
                  onClick={() => handleResourceClick(resource)}
                  sx={{ 
                    height: '100%', 
                    display: 'flex', 
                    flexDirection: 'column',
                    cursor: 'pointer',
                    transition: 'all 0.3s ease',
                    '&:hover': {
                      transform: 'translateY(-4px)',
                      boxShadow: 6,
                    },
                  }}>
                  <CardMedia
                    component="img"
                    height="250"
                    image={resource.coverImageUrl || resource.coverUrl || '/covers/movie_cover_2.jpg'}
                    alt={resource.title}
                  />
                  <CardContent sx={{ flexGrow: 1 }}>
                    <Typography gutterBottom variant="h6" component="div">
                      {resource.title}
                    </Typography>
                    <Box sx={{ mb: 1 }}>
                      {resource.description && (
                        <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                          {resource.description.length > 50 ? `${resource.description.substring(0, 50)}...` : resource.description}
                        </Typography>
                      )}
                    </Box>
                    <Typography variant="body2" color="text.secondary">
                      上传者：{resource.uploaderName || '未知'}
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
            ))}
          </Grid>
        )}
        
        {/* 分页组件 */}
        {!loading && !error && recommendedResources.length > 0 && (
          <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
            <Pagination 
              count={totalPages} 
              page={page} 
              onChange={(event, value) => setPage(value)}
              color="primary" 
              showFirstButton 
              showLastButton
            />
          </Box>
        )}
      </Box>
    </Container>
  );
};

export default Home;